import {
  View,
  Text,
  StatusBar,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  FlatList,
} from 'react-native';
import React, {useState} from 'react';
import {useTheme} from '@react-navigation/native';
import {useSelector, useDispatch} from 'react-redux';
import {changePopularData, fetchPopular} from '../../store/popular.js';
import PopularItem from '../../components/PopularItem.jsx';

export default function Search() {
  const {colors} = useTheme();
  const popular = useSelector(state => state.popular);
  const dispatch = useDispatch();

  const [value, setValue] = useState('');

  const handleSearch = () => {
    dispatch(fetchPopular({type: value, key: value, refresh: true}));
  };

  const changeFavorite = item => {
    dispatch(changePopularData({item, key: value}));
  };

  const renderItem = ({item}) => {
    return <PopularItem item={item} changeFavorite={changeFavorite} />;
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" />
      <View style={styles.search}>
        <TextInput
          style={[styles.input, {borderColor: colors.primary}]}
          autoFoucs
          value={value}
          onChangeText={setValue}
          placeholder="请输入"
        />
        <TouchableOpacity
          style={[styles.title, {backgroundColor: colors.primary}]}
          onPress={handleSearch}>
          <Text style={styles.text}>搜索</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.container}>
        {popular.refresh ? (
          <ActivityIndicator
            size={'large'}
            animating={popular.refresh}
            style={styles.loading}
          />
        ) : (
          <FlatList
            data={popular.popularData[value]}
            keyExtractor={item => item.id}
            renderItem={renderItem}
          />
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 10,
  },
  loading: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  input: {
    height: 40,
    borderWidth: 1,
    flex: 1,
    marginLeft: 10,
    borderRadius: 2,
  },
  title: {
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 10,
    paddingLeft: 10,
    paddingRight: 10,
    height: 40,
    borderRadius: 2,
  },
  text: {
    fontSize: 14,
    color: '#FFF',
  },
  search: {
    alignItems: 'center',
    flexDirection: 'row',
    height: 40,
    marginRight: 10,
  },
});
